from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import JSONResponse

from .exceptions import CustomHTTPException
from .oauth import verify_token


class TokenAuthMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        # 需要排除 Token 验证的路由
        exempt_routes = ["/docs", "/redoc", "/openapi.json", "/swagger-ui/oauth2-redirect", "/static",
                         ]
        if request.url.path == "/" \
                or any(request.url.path.startswith(route) for route in exempt_routes) \
                or not request.url.path.startswith("/v1"):
            # 没有鉴权但是必须指定变量才能确定数据库
            license_no = request.headers.get("license_no") or request.query_params.get("license_no")
            project_class = request.headers.get("project_class") or request.query_params.get("project_class")
            request.state.token_info = {"license_no": license_no, "project_class": project_class}
            return await call_next(request)

        # auth_header = request.headers.get("Authorization")
        # if not auth_header or not auth_header.startswith("Bearer "):
        #     return JSONResponse({"detail": "缺失访问权限Token"}, 401)
        # try:
        #     token = auth_header.split(" ")[1]
        #     res = verify_token(token)
        #     res.update({"token": token})
        #     request.state.token_info = res
        # except CustomHTTPException as e:
        #     return JSONResponse(e.custom_resp, e.status_code)

        response = call_next(request)
        return await response
